/*
 * Downloader.cpp
 *
 *  Created on: Feb 23, 2011
 *      Author: MongKieu
 */

#include "../inc/Utility/Downloader.h"
#include "../inc/Ui/WeatherForm.h"

using namespace Osp::Net;
using namespace Osp::Net::Http;
using namespace Osp::Base;
using namespace Osp::Io;
DownloadListener::DownloadListener(String url, String path,
		IDownloadFinishedListener* finishListener) {
	__url = new String(url);
	__path = new String(path);
	__finishListener = finishListener;

}

void DownloadListener::OnTransactionReadyToRead(HttpSession &httpSession,
		HttpTransaction &httpTransaction, int availableBodyLen) {
	AppLog("Vao  on transaction ready to read");
	HttpResponse* pResponse = httpTransaction.GetResponse();

	NetHttpStatusCode code = pResponse->GetStatusCode();

	ByteBuffer* pBody = pResponse->ReadBodyN();
	__finishListener->OnDataDownloadComplete(code, pBody);
	//if the HTTP code is not 200, call falied and terminate
	if (code != NET_HTTP_STATUS_OK) {
		__finishListener->OnDownloadFailed(*__url, *__path);
	}

	//try to save the file, if error: call failed and terminate
	if (__path->GetLength() > 0){
		if (SaveFile(pBody, *__path) != E_SUCCESS) {
			__finishListener->OnDownloadFailed(*__url, *__path);
		}
	}
	//call success and terminate
	__finishListener->OnDownloadComplete(*__url, *__path);
	terminate(httpSession, httpTransaction);
}

//something went wrong while downloading: network error, no connection, erroneuous uri, etc.

void DownloadListener::OnTransactionAborted(HttpSession &httpSession,
		HttpTransaction &httpTransaction, result r) {
	AppLog("Vao ontransaction Aborted");
	__finishListener->OnDownloadFailed(*__url, *__path); //notify our DownloadFinishedListener
	//terminate(httpSession, httpTransaction); //cleanup our mess
	AppLog("Ket thuc ontransaction Aborted");
}

//save the buffer to the specified file
int DownloadListener::SaveFile(ByteBuffer* content, String path) {
	AppLog("Vao  save file");

	File file;
	result r = E_SUCCESS;
	r = file.Construct(path, L"w+");
	if (r == E_INVALID_STATE) //  This instance has already been constructed.
	{
		AppLog("E_INVALID_STATE");
	}
	if (r == E_INVALID_ARG) //  Overall length of the given path equals zero or exceeds the system limitation. The given path contains prohibited character(s). The given path is invalid. The given open mode is a non-allowed combination.
	{
		AppLog("E_INVALID_ARG");
	}
	if (r == E_ILLEGAL_ACCESS) //  The specified path does not begin with '/Home' (or '/Home/Share', '/Share/[appid]', '/Res', '/Media/Images', '/Media/Sounds', '/Media/Videos', '/Media/Themes', '/Media/Others', '/Storagecard/Media/Images', '/Storagecard/Media/Sounds', '/Storagecard/Media/Videos', '/Storagecard/Media/Themes', '/Storagecard/Media/Others'). Access denied due to insufficient permission (That is, opening a read-only file in the write mode or opening a file that was previously opened in the no-sharing mode.)
	{
		AppLog("E_ILLEGAL_ACCESS");
	}
	if (r == E_IO)
	{
		AppLog("E_IO");
	}
		// E_IO

	if(IsFailed(r)) {return r;
		/*return if the file access couldn't be setup*/
	}
	r = file.Write(*content);
	AppLog("Ket thuc  save file");
	return r;

}

	// cleanup after we are done. Just delete everything we do not need any more.
void DownloadListener::terminate(HttpSession &httpSession,
		HttpTransaction &httpTransaction) {
	delete &httpTransaction;
	delete &httpSession;
	delete __url;
	delete __path;
	//delete __finishListener;
	//delete this;
}
int Downloader::downloadAndSave(String url, String path,
		IDownloadFinishedListener* finishListener) {

	AppLog("Vao download save");
	result r = E_SUCCESS;
	HttpSession* __pSession = new HttpSession();
	r = __pSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, url, null);

	if (IsFailed(r)) {
		finishListener->OnDownloadFailed(url, path);
		return r;
	}

	HttpTransaction* __pTransaction = __pSession->OpenTransactionN();
	if (null == __pTransaction) {
		finishListener->OnDownloadFailed(url, path);
		r = E_FAILURE;
		return r;
	}

	r = __pTransaction->AddHttpTransactionListener(*(new DownloadListener(url,
			path, finishListener)));
	if (IsFailed(r)) {
		finishListener->OnDownloadFailed(url, path);
		return r;
	}

	HttpRequest* pRequest = __pTransaction->GetRequest();

	if (pRequest == null) {
		finishListener->OnDownloadFailed(url, path);
		r = E_FAILURE;
		return r;
	}

	r = pRequest->SetUri(url);
	if (IsFailed(r)) {
		finishListener->OnDownloadFailed(url, path);
		return r;
	}
	AppLog("Ket thuc download save");

	r = pRequest->SetMethod(NET_HTTP_METHOD_GET);

	if (IsFailed(r)) {
		finishListener->OnDownloadFailed(url, path);
		return r;
	}
	r = __pTransaction->Submit();

	if (IsFailed(r)) {
		finishListener->OnDownloadFailed(url, path);
	}

	return r;
}

